<script setup lang="tsx">
import { computed, h, reactive, ref } from 'vue';
import { Popconfirm, message } from 'ant-design-vue';
import { fetchBatchDeleteTenants, fetchDeleteTenant, fetchGetTenantList } from '@/service/api';
import { enableStatusRecord } from '@/constants/business';
import { $t } from '@/locales';
// import { useAuth } from '@/hooks/business/auth';
import TableHeaderOperation from '@/components/advanced/table-header-operation.vue';
import AuthButton from '@/components/common/auth-button.vue';
import TenantOperateDrawer from './modules/tenant-operate-drawer.vue';
import TenantViewDrawer from './modules/tenant-view-drawer.vue';
import TenantSearch from './modules/tenant-search.vue';

// 权限检查
// const { hasAuthSync } = useAuth();

// 响应式数据
const loading = ref(false);
const data = ref<Api.SystemManage.Tenant[]>([]);
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true
});

const searchParams = reactive({
  current: 1,
  size: 10,
  tenantCode: undefined,
  tenantName: undefined,
  status: undefined,
  contactName: undefined
});

// 抽屉相关
const drawerVisible = ref(false);
const operateType = ref<'add' | 'edit'>('add');
const editingData = ref<Api.SystemManage.Tenant | null>(null);

// 查看功能状态
const viewDrawerVisible = ref(false);
const viewingData = ref<Api.SystemManage.Tenant | null>(null);

// 选择相关
const selectedRowKeys = ref<number[]>([]);
const rowSelection = computed(() => ({
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys: any[]) => {
    selectedRowKeys.value = keys as number[];
  }
}));

// 表格列配置
const columns = ref([
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
    width: 80,
    customRender: ({ index }: { index: number }) => index + 1
  },
  {
    title: '租户编码',
    dataIndex: 'tenantCode',
    key: 'tenantCode',
    width: 120
  },
  {
    title: '租户名称',
    dataIndex: 'tenantName',
    key: 'tenantName',
    width: 150
  },
  {
    title: '租户描述',
    dataIndex: 'description',
    key: 'description',
    width: 150,
    ellipsis: true
  },
  {
    title: '联系人',
    dataIndex: 'contactName',
    key: 'contactName',
    width: 100
  },
  {
    title: '联系电话',
    dataIndex: 'contactPhone',
    key: 'contactPhone',
    width: 120
  },
  {
    title: '联系邮箱',
    dataIndex: 'contactEmail',
    key: 'contactEmail',
    width: 150,
    ellipsis: true
  },
  {
    title: '租户域名',
    dataIndex: 'tenantDomain',
    key: 'tenantDomain',
    width: 150
  },
  {
    title: '过期时间',
    dataIndex: 'expireTime',
    key: 'expireTime',
    width: 120
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
    customRender: ({ record }: { record: Api.SystemManage.Tenant }) => {
      const tagMap: Record<Api.Common.EnableStatus, string> = {
        '1': 'success',
        '2': 'warning'
      };
      const label = $t(enableStatusRecord[record.status]);
      return h('ATag', { color: tagMap[record.status] }, label);
    }
  },
  {
    title: '操作',
    key: 'operate',
    width: 150,
    fixed: 'right' as const,
    customRender: ({ record }: { record: Api.SystemManage.Tenant }) => (
      <div class="flex items-center gap-3px">
        <AuthButton
          permission="TENANT_VIEW"
          type="link"
          size="small"
          class="h-auto p-0 text-blue-500 hover:text-blue-600"
          onClick={() => handleView(record)}
        >
          查看
        </AuthButton>
        <AuthButton
          permission="TENANT_EDIT"
          type="link"
          size="small"
          class="h-auto p-0 text-blue-500 hover:text-blue-600"
          onClick={() => handleEdit(record)}
        >
          编辑
        </AuthButton>
        <Popconfirm
          title="确认删除此租户吗？"
          okText="确认"
          cancelText="取消"
          onConfirm={() => handleDelete(record.id)}
        >
          <AuthButton
            permission="TENANT_DELETE"
            type="link"
            size="small"
            class="h-auto p-0 text-red-500 hover:text-red-600"
          >
            删除
          </AuthButton>
        </Popconfirm>
      </div>
    )

    // 过滤显示逻辑已整合到JSX的条件渲染中
  }
]);

// 获取数据
async function getData() {
  try {
    loading.value = true;
    const response = await fetchGetTenantList(searchParams);
    if (response && response.data) {
      data.value = response.data.records || [];
      pagination.total = Number(response.data.total) || 0;
      pagination.current = Number(response.data.current) || 1;
      pagination.pageSize = Number(response.data.size) || 10;
    }
  } catch {
    message.error('获取数据失败');
  } finally {
    loading.value = false;
  }
}

// 搜索
function handleSearch() {
  searchParams.current = 1;
  getData();
}

// 重置搜索
function handleReset() {
  Object.assign(searchParams, {
    current: 1,
    size: 10,
    tenantCode: undefined,
    tenantName: undefined,
    status: undefined,
    contactName: undefined
  });
  getData();
}

// 分页变化
function handleTableChange(pag: any) {
  searchParams.current = pag.current;
  searchParams.size = pag.pageSize;
  getData();
}

// 新增
function handleAdd() {
  operateType.value = 'add';
  editingData.value = null;
  drawerVisible.value = true;
}

// 编辑
function handleEdit(record: Api.SystemManage.Tenant) {
  operateType.value = 'edit';
  editingData.value = record;
  drawerVisible.value = true;
}

// 查看租户详情
function handleView(record: Api.SystemManage.Tenant) {
  viewingData.value = record;
  viewDrawerVisible.value = true;
}

// 删除
async function handleDelete(id: number) {
  try {
    await fetchDeleteTenant(id);
    message.success('删除成功');
    getData();
  } catch {
    message.error('删除失败');
  }
}

// 批量删除
async function handleBatchDelete() {
  if (selectedRowKeys.value.length === 0) {
    message.warning('请选择要删除的租户');
    return;
  }

  try {
    await fetchBatchDeleteTenants(selectedRowKeys.value);
    message.success('批量删除成功');
    selectedRowKeys.value = [];
    getData();
  } catch {
    message.error('批量删除失败');
  }
}

// 抽屉成功回调
function handleDrawerSuccess() {
  getData();
}

// 初始化
getData();
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <TenantSearch v-model:model="searchParams" @reset="handleReset" @search="handleSearch" />
    <ACard
      title="租户管理"
      :bordered="false"
      :body-style="{ flex: 1, overflow: 'hidden' }"
      class="flex-col-stretch sm:flex-1-hidden card-wrapper"
    >
      <template #extra>
        <TableHeaderOperation
          :disabled-delete="selectedRowKeys.length === 0"
          :loading="loading"
          add-permission="TENANT_ADD"
          delete-permission="TENANT_DELETE"
          @add="handleAdd"
          @delete="handleBatchDelete"
          @refresh="getData"
        />
      </template>

      <ATable
        :columns="columns"
        :data-source="data"
        :loading="loading"
        :pagination="pagination"
        :row-selection="rowSelection"
        row-key="id"
        size="small"
        :scroll="{ x: 'max-content' }"
        @change="handleTableChange"
      />
    </ACard>
    <TenantOperateDrawer
      v-model:open="drawerVisible"
      :operate-type="operateType"
      :editing-data="editingData"
      @success="handleDrawerSuccess"
    />

    <!-- 查看租户详情抽屉 -->
    <TenantViewDrawer v-model:model-value="viewDrawerVisible" title="查看租户详情" :width="600">
      <div v-if="viewingData" class="tenant-view-content">
        <ARow :gutter="16">
          <ACol :span="12">
            <div class="info-item">
              <label class="info-label">租户编码：</label>
              <span class="info-value">{{ viewingData.tenantCode }}</span>
            </div>
          </ACol>
          <ACol :span="12">
            <div class="info-item">
              <label class="info-label">租户名称：</label>
              <span class="info-value">{{ viewingData.tenantName }}</span>
            </div>
          </ACol>
          <ACol :span="24">
            <div class="info-item">
              <label class="info-label">租户描述：</label>
              <span class="info-value">{{ viewingData.description || '-' }}</span>
            </div>
          </ACol>
          <ACol :span="12">
            <div class="info-item">
              <label class="info-label">联系人：</label>
              <span class="info-value">{{ viewingData.contactName || '-' }}</span>
            </div>
          </ACol>
          <ACol :span="12">
            <div class="info-item">
              <label class="info-label">联系电话：</label>
              <span class="info-value">{{ viewingData.contactPhone || '-' }}</span>
            </div>
          </ACol>
          <ACol :span="12">
            <div class="info-item">
              <label class="info-label">联系邮箱：</label>
              <span class="info-value">{{ viewingData.contactEmail || '-' }}</span>
            </div>
          </ACol>
          <ACol :span="12">
            <div class="info-item">
              <label class="info-label">租户域名：</label>
              <span class="info-value">{{ viewingData.tenantDomain || '-' }}</span>
            </div>
          </ACol>
          <ACol :span="12">
            <div class="info-item">
              <label class="info-label">过期时间：</label>
              <span class="info-value">{{ viewingData.expireTime || '-' }}</span>
            </div>
          </ACol>
          <ACol :span="12">
            <div class="info-item">
              <label class="info-label">状态：</label>
              <span class="info-value">
                <ATag v-if="viewingData.status" :color="viewingData.status === '1' ? 'success' : 'warning'">
                  {{ viewingData.status === '1' ? '启用' : '禁用' }}
                </ATag>
                <span v-else>-</span>
              </span>
            </div>
          </ACol>
        </ARow>
      </div>
    </TenantViewDrawer>
  </div>
</template>

<style scoped>
.tenant-view-content {
  padding: 16px 0;
}

.info-item {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}

.info-label {
  font-weight: 500;
  color: #666;
  min-width: 80px;
  margin-right: 8px;
}

.dark .info-label {
  color: #cbd5e1;
}

.info-value {
  color: #333;
  flex: 1;
}

.dark .info-value {
  color: #f8fafc;
}
</style>

<style scoped></style>
